package com.jkb.wbfl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.ansj.domain.Term;

import org.ansj.splitWord.analysis.ToAnalysis;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Mapper.Context;

import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.JiebaSegmenter.SegMode;
import com.huaban.analysis.jieba.SegToken;

/**
 * 
 * @author wangbin
 * 功能：对多篇文章进行分类
 * 输入：文章\t\t\turl
 * 输出：文章\t\t\t文章类别\t\t\turl
 * 使用算法：比较余弦相似度
 * 运行步骤：第五步
 *
 */
public class FenLeiMR {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		//args0:dst
		//args1:out
		//args2:splitMB
		//args3:加载词与类别和tfidf对应关系
		//args4:加载词与idf对应关系
		//args5:加载停用词路径
		if(args.length != 6){
			System.out.println("args0:dst");
			System.out.println("args1:out");
			System.out.println("args2:splitMB");
			System.out.println("args3:加载词与类别和tfidf对应关系");
			System.out.println("args4:加载词与idf对应关系");
			System.out.println("args5:加载停用词路径");
			System.exit(0);
		}
		
		int SplitMB = Integer.valueOf(args[2]);
		String dst = args[0];
		String out = args[1];
		Configuration conf = new Configuration();
		conf.set("mapreduce.input.fileinputformat.split.maxsize", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapred.min.split.size", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.node", String.valueOf(SplitMB * 1024 * 1024));
		conf.set("mapreduce.input.fileinputformat.split.minsize.per.rack", String.valueOf(SplitMB * 1024 * 1024));
		Job job =  Job.getInstance(conf);
		FileInputFormat.addInputPath(job, new Path(dst));
		FileOutputFormat.setOutputPath(job, new Path(out));
		
		job.addCacheFile(new Path(args[3]).toUri());
		job.addCacheFile(new Path(args[4]).toUri());
		job.addCacheFile(new Path(args[5]).toUri());
		job.addFileToClassPath(new Path("/edu/jarpackage/jieba-analysis-1.0.0.jar"));
		job.setMapperClass(FenLeiMap.class);
		
		job.setNumReduceTasks(0);
		
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		
		job.setJarByClass(FenLeiMR.class);
        job.waitForCompletion(true);
		
	}
	
	public static class FenLeiMap extends Mapper<Object,Text,Text,Text>{
		//加载词与类别和tfidf对应关系
		//词<类型:TFIDF>
		HashMap<String,HashMap<String,Double>> TFIDFS = new HashMap<String,HashMap<String,Double>>();
		
		//加载词与idf对应关系
		//词：IDF
		HashMap<String,Double> IDF = new HashMap<String,Double>();
		
		public final static String SP = "\t\t\t";
		
		//停用词容器
		HashSet<String> stopwords = new HashSet<String>();
		
		@Override
		public void setup(Context context) throws IOException{
		    
			//Path[] paths = context.getLocalCacheFiles();
			URI[] paths = context.getCacheFiles();
			//加载词与类别和tfidf对应关系
			BufferedReader tfidfreader = new BufferedReader(new FileReader(paths[0].toString()));
			String line;
			while((line = tfidfreader.readLine()) != null){
				String[] tp = line.split("\t");
				HashMap<String,Double> type_tfidf = new HashMap<String,Double>();
				type_tfidf.put(tp[1], Double.valueOf(tp[2]));
				TFIDFS.put(tp[0], type_tfidf);
			}
			
			//加载词与idf对应关系
			BufferedReader idfreader = new BufferedReader(new FileReader(paths[1].toString()));
			String idfline;
			while((idfline = idfreader.readLine()) != null){
				String[] tp = idfline.split("\t");
				IDF.put(tp[0], Double.valueOf(tp[1]));
			}
			
			//加载停用词
			BufferedReader stopreader = new BufferedReader(new FileReader(paths[2].toString()));
			String stopline;
			while((stopline = stopreader.readLine()) != null){
				stopwords.add(stopline);
			}
		}
		
		@Override
		public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
			String[] line = value.toString().split(SP);			
			if(line.length >= 2){
				String article = line[0];
				String url = line[1];
				/*对文章进行分词*/
				JiebaSegmenter Segmenter = new JiebaSegmenter();
				List<SegToken> STList = Segmenter.process(article.toString(), SegMode.SEARCH);
				//记录词和词出现在本文的数量
				HashMap<String,Integer> map = new HashMap<String,Integer>();
				//本文章（一篇文章）词与tfidf值对应关系
				HashMap<String,Double> tfidfs = new HashMap<String,Double>();
				//获取训练数据分类下该词的tfidf(分类：词：tfidf)
				HashMap<String,HashMap<String,Double>> trainData = new HashMap<String,HashMap<String,Double>>();
				int count = 0;
				/*获取词在文章中出现的数量和本文章所有词的数量,为求词在本文中的TF*/
				for(SegToken st : STList){
					try{
					
						String wd =st.word;//.getToken();
						if(stopwords.contains(wd)) continue;
						if(map.containsKey(wd)){
							int i = map.get(wd).intValue() + 1;
							map.put(wd, Integer.valueOf(i));
						}else{
							map.put(wd, Integer.valueOf(1));
						}
						count++;
					}catch(Exception e){
						System.out.println(e.toString());
					}
				}
				/*生成文章tfidf,获取训练词的tfidf*/
				for (Map.Entry<String,Integer> entry : map.entrySet()){
					String w = entry.getKey();//词
					int incr = entry.getValue().intValue();
					if(IDF.containsKey(w)){
						if(TFIDFS.containsKey(w)){
							double idf = IDF.get(w);
							double tf = (double)incr/count;//计算本文某词的tf值
							double tfidf = tf*idf;//生成文章tfidf,生成本文某词的tfidf值
							tfidfs.put(w, Double.valueOf(tfidf));
							//从训练数据中获取该词分类下的tfidf(类别-tfidf)
							HashMap<String,Double> fl = TFIDFS.get(w);
							//获取训练词的tfidf,从训练数据中生成本文分词中词与其他分类的关系(分类：词：tfidf)
							for (Map.Entry<String,Double> fl_entry : fl.entrySet()){
								//类型
								String fl_type = fl_entry.getKey();
								//tfidf
								double fl_tfidf = fl_entry.getValue().doubleValue();
								if(trainData.containsKey(fl_type)){
									trainData.get(fl_type).put(w, Double.valueOf(fl_tfidf));
								}else{
									//词：tfidf
									HashMap<String,Double> ci = new HashMap<String,Double>();
									ci.put(w, Double.valueOf(fl_tfidf));
									trainData.put(fl_type, ci);
								}
							}
						}
						
					}

				}
				//计算cos
				//最大（靠近1）的cos值
				double tmp_cos = 0;
				//判定的类别
				String tmp_type = "";
				//按照类别循环
				for(Map.Entry<String,HashMap<String,Double>> entry : trainData.entrySet()){
					//分子
					double numerator = 0;
					//此文章测试向量分母部分
					double test_denominator = 0;
					//训练特征向量分母部分
					double train_denominator = 0;
					//按照测试文章分词进行循环
					//tfidfs:本文章（一篇文章）词与tfidf值对应关系
					for(Map.Entry<String,Double> article_entry : tfidfs.entrySet()){
						String article_word = article_entry.getKey();//词
						double article_tfidf = article_entry.getValue().doubleValue();
						double train_tfidf = 0;
						//已训练某个类别下的词和tfidf
						HashMap<String,Double> ws = entry.getValue();
						if(ws.containsKey(article_word)){
							train_tfidf = ws.get(article_word).doubleValue();
						}
						numerator += (article_tfidf*train_tfidf);
						test_denominator += Math.pow(article_tfidf, 2);
						train_denominator += Math.pow(train_tfidf, 2);
					}
					double cos = numerator / (Math.sqrt(train_denominator) * Math.sqrt(test_denominator));
					//取cos靠近1的值
					if(cos > tmp_cos){
						tmp_cos = cos;
						tmp_type = entry.getKey();
					}
				}
				context.write(new Text(article + SP + tmp_type + "\t\t"),new Text(url));
				
			}
			
		}
	}
	

}
